<template>
  <div class="manual-control-container">
    <!-- 头部控制栏 -->
    <div class="control-header">
      <div class="header-left">
        <el-icon class="control-icon"><Operation /></el-icon>
        <span class="control-title">手动控制</span>
      </div>
      

    </div>
    
    <!-- 机器狗控制面板 -->
    <div class="robot-control-panel">
      <!-- 手动控制区域 -->
      <div class="manual-controls">
        <!-- 虚拟操纵杆 -->
        <div class="joystick-section">
          <h4 class="section-title">移动控制</h4>
          <div class="joystick-control-panel">
            <div class="joystick-container" ref="joystickContainer">
              <div class="joystick-background">
                <div 
                  class="joystick-handle" 
                  ref="joystickHandle"
                  @mousedown="startJoystickDrag"
                  :style="joystickStyle"
                ></div>
              </div>
            </div>
            
            <!-- 方向按钮围绕操纵杆 -->
            <div class="direction-buttons-overlay">
              <button class="dir-btn dir-up" @mousedown="startMove('forward')" @mouseup="stopMove">
                <el-icon><ArrowUp /></el-icon>
              </button>
              <button class="dir-btn dir-left" @mousedown="startMove('left')" @mouseup="stopMove">
                <el-icon><ArrowLeft /></el-icon>
              </button>
              <button class="dir-btn dir-right" @mousedown="startMove('right')" @mouseup="stopMove">
                <el-icon><ArrowRight /></el-icon>
              </button>
              <button class="dir-btn dir-down" @mousedown="startMove('backward')" @mouseup="stopMove">
                <el-icon><ArrowDown /></el-icon>
              </button>
            </div>
          </div>
        </div>
        
        <!-- 动作控制 -->
        <div class="action-controls">
          <h4 class="section-title">动作控制</h4>
          <div class="action-buttons">
            <button 
              class="action-btn" 
              :class="{ active: robotState.posture === 'stand' }"
              @click="setPosture('stand')"
            >
              站立
            </button>
            <button 
              class="action-btn" 
              :class="{ active: robotState.posture === 'sit' }"
              @click="setPosture('sit')"
            >
              坐下
            </button>
            <button 
              class="action-btn" 
              :class="{ active: robotState.posture === 'lie' }"
              @click="setPosture('lie')"
            >
              趴下
            </button>
          </div>
          
          <!-- 速度控制 -->
          <div class="speed-control">
            <label class="section-title">移动速度</label>
            <el-slider 
              v-model="robotState.speed" 
              :min="0" 
              :max="100" 
              :step="10"
              show-stops
              @change="updateSpeed"
            />
          </div>
          

          
          <!-- 紧急停止 -->
          <button class="emergency-stop" @click="emergencyStop">
            <el-icon><CircleClose /></el-icon>
            紧急停止
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { 
  Operation, Refresh, CircleClose, ArrowUp, ArrowDown, 
  ArrowLeft, ArrowRight 
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 定义 emits
const emit = defineEmits(['movement-command', 'posture-change', 'speed-change', 'emergency-stop'])

const joystickContainer = ref(null)
const joystickHandle = ref(null)

const robotState = reactive({
  posture: 'stand',
  speed: 50,
  isMoving: false,
  direction: null,
  battery: 85,
  status: '待命中'
})

const joystickState = reactive({
  isDragging: false,
  x: 0,
  y: 0,
  centerX: 60,
  centerY: 60,
  maxRadius: 40
})

const joystickStyle = ref({
  left: '50%',
  top: '50%',
  transform: 'translate(-50%, -50%)'
})

// 操纵杆控制
const startJoystickDrag = (event) => {
  joystickState.isDragging = true
  document.addEventListener('mousemove', onJoystickDrag)
  document.addEventListener('mouseup', endJoystickDrag)
}

const onJoystickDrag = (event) => {
  if (!joystickState.isDragging) return
  
  const rect = joystickContainer.value.getBoundingClientRect()
  const centerX = rect.left + rect.width / 2
  const centerY = rect.top + rect.height / 2
  
  let deltaX = event.clientX - centerX
  let deltaY = event.clientY - centerY
  
  const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
  
  if (distance > joystickState.maxRadius) {
    deltaX = (deltaX / distance) * joystickState.maxRadius
    deltaY = (deltaY / distance) * joystickState.maxRadius
  }
  
  joystickState.x = deltaX
  joystickState.y = deltaY
  
  joystickStyle.value = {
    left: `${50 + (deltaX / joystickState.maxRadius) * 50}%`,
    top: `${50 + (deltaY / joystickState.maxRadius) * 50}%`,
    transform: 'translate(-50%, -50%)'
  }
  
  // 发送移动指令
  sendMovementCommand(deltaX, deltaY)
}

const endJoystickDrag = () => {
  joystickState.isDragging = false
  joystickState.x = 0
  joystickState.y = 0
  
  joystickStyle.value = {
    left: '50%',
    top: '50%',
    transform: 'translate(-50%, -50%)'
  }
  
  document.removeEventListener('mousemove', onJoystickDrag)
  document.removeEventListener('mouseup', endJoystickDrag)
  
  stopMove()
}

// 方向按钮控制
const startMove = (direction) => {
  robotState.isMoving = true
  robotState.direction = direction
  robotState.status = '移动中'
  
  // 发送移动指令到父组件
  emit('movement-command', { type: 'start', direction })
  console.log(`开始移动: ${direction}`)
}

const stopMove = () => {
  robotState.isMoving = false
  robotState.direction = null
  robotState.status = '待命中'
  
  emit('movement-command', { type: 'stop' })
  console.log('停止移动')
}

// 姿态控制
const setPosture = (posture) => {
  robotState.posture = posture
  emit('posture-change', posture)
  console.log(`设置姿态: ${posture}`)
  ElMessage.success(`切换到${posture === 'stand' ? '站立' : posture === 'sit' ? '坐下' : '趴下'}姿态`)
}

// 速度控制
const updateSpeed = (speed) => {
  emit('speed-change', speed)
  console.log(`更新速度: ${speed}%`)
}

// 紧急停止
const emergencyStop = () => {
  robotState.isMoving = false
  robotState.direction = null
  robotState.status = '紧急停止'
  
  // 重置操纵杆
  joystickState.x = 0
  joystickState.y = 0
  joystickStyle.value = {
    left: '50%',
    top: '50%',
    transform: 'translate(-50%, -50%)'
  }
  
  emit('emergency-stop')
  ElMessage.warning('紧急停止已激活')
  console.log('紧急停止')
}

// 重置所有控制
const resetAllControls = () => {
  robotState.posture = 'stand'
  robotState.speed = 50
  robotState.isMoving = false
  robotState.direction = null
  robotState.status = '待命中'
  
  // 重置操纵杆
  joystickState.x = 0
  joystickState.y = 0
  joystickStyle.value = {
    left: '50%',
    top: '50%',
    transform: 'translate(-50%, -50%)'
  }
  
  ElMessage.info('控制面板已重置')
}

// 移动指令
const sendMovementCommand = (x, y) => {
  const intensity = Math.sqrt(x * x + y * y) / joystickState.maxRadius
  const angle = Math.atan2(y, x)
  
  emit('movement-command', { 
    type: 'joystick', 
    intensity, 
    angle,
    x,
    y
  })
  
  console.log(`移动指令 - 强度: ${intensity.toFixed(2)}, 角度: ${angle.toFixed(2)}`)
}

// 获取状态样式类
const getStatusClass = () => {
  switch (robotState.status) {
    case '移动中':
      return 'status-moving'
    case '紧急停止':
      return 'status-emergency'
    case '待命中':
    default:
      return 'status-ready'
  }
}

// 暴露方法供父组件调用
defineExpose({
  emergencyStop,
  resetAllControls,
  robotState
})

onUnmounted(() => {
  document.removeEventListener('mousemove', onJoystickDrag)
  document.removeEventListener('mouseup', endJoystickDrag)
})
</script>

<style scoped>
.manual-control-container {
  background: rgba(10, 25, 47, 0.9);
  backdrop-filter: blur(8px);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  box-shadow: 0px 4px 12px 0px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.control-header {
  background: var(--secondary-bg);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 8px;
  height: 28px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 4px;
}

.control-icon {
  color: var(--primary-blue);
  font-size: 14px;
}

.control-title {
  color: var(--text-primary);
  font-size: 13px;
  font-weight: 500;
  line-height: 1;
}



.robot-control-panel {
  background: var(--primary-bg);
  padding: 4px 4px 8px 4px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.manual-controls {
  display: flex;
  flex-direction: column;
  flex: 1;
  justify-content: space-between;
}

.section-title {
  color: var(--text-primary);
  font-size: 12px;
  font-weight: 600;
  margin: 0 0 3px 0;
  text-align: left;
  align-self: flex-start;
}

.joystick-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  flex: 0 0 auto;
}

.joystick-control-panel {
  position: relative;
  width: 140px;
  height: 140px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.joystick-container {
  position: relative;
  width: 80px;
  height: 80px;
  z-index: 2;
}

.joystick-background {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: var(--secondary-bg);
  border: 2px solid var(--border-color);
  position: relative;
}

.joystick-handle {
  position: absolute;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: var(--primary-blue);
  cursor: pointer;
  transition: all 0.1s ease;
  box-shadow: 0 2px 8px rgba(96, 165, 250, 0.3);
}

.direction-buttons-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.dir-btn {
  position: absolute;
  width: 28px;
  height: 28px;
  background: var(--accent-bg);
  border: none;
  border-radius: 4px;
  color: var(--text-secondary);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.dir-btn:hover {
  background: var(--secondary-bg);
  color: var(--primary-blue);
}

.dir-btn:active {
  background: var(--primary-blue);
  color: var(--text-primary);
}

.dir-up {
  top: 0;
  left: 50%;
  transform: translateX(-50%);
}

.dir-down {
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
}

.dir-left {
  left: 0;
  top: 50%;
  transform: translateY(-50%);
}

.dir-right {
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

.action-controls {
  display: flex;
  flex-direction: column;
  flex: 1;
  justify-content: space-between;
}

.action-buttons {
  display: flex;
  gap: 4px;
  flex: 0 0 auto;
}

.action-btn {
  flex: 1;
  padding: 6px 8px;
  background: var(--accent-bg);
  border: none;
  border-radius: 4px;
  color: var(--text-secondary);
  font-size: 11px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background: var(--secondary-bg);
}

.action-btn.active {
  background: var(--primary-blue);
  color: var(--text-primary);
}

.speed-control {
  display: flex;
  flex-direction: column;
  gap: 2px;
  flex: 0 0 auto;
}

.emergency-stop {
  background: #DC2626;
  border: none;
  border-radius: 4px;
  color: white;
  padding: 6px 8px;
  font-size: 11px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 3px;
  transition: all 0.3s ease;
}

.emergency-stop:hover {
  background: #B91C1C;
}
</style>>